package com.linchong.jvm.monitor;



/**
 * @author linchong
 * @version 1.0
 * @Date: 2020-12-03 16:04
 * @Description: ThreadLockTest$
 */
public class ThreadLockTest {

	public static void main(String[] args) {
		AModel am = new AModel("mys1","mys2");
		for (int i = 0; i < 10; i++) {
			Thread t1 = new Thread(new MyThread1(am));
			t1.setName("MyThread1");
			t1.start();

			Thread t2 = new Thread(new MyThread2(am));
			t2.setName("MyThread2");
			t2.start();

		}
	}

}

class AModel{
	public String s1;
	public String s2;

	public AModel(String s1,String s2){
		this.s1 = s1;
		this.s2 = s2;
	}
}

class MyThread1 implements Runnable{

	private AModel am = null;

	public MyThread1(AModel am){
		this.am = am;
	}
	@Override
	public void run() {
		synchronized (am.s1){
			System.out.println("now in my-thread1,has am.s1");
			try {
				Thread.sleep(1_000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			System.out.println("now thread1 begin am.s2");

			synchronized (am.s2){
				System.out.println("1---> Thread id="+ Thread.currentThread().getId()
						+"s1="+am.s1+",s2="+am.s2);
			}
		}
	}
}


class MyThread2 implements Runnable{

	private AModel am = null;

	public MyThread2(AModel am){
		this.am = am;
	}
	@Override
	public void run() {
		synchronized (am.s2){
			System.out.println("now in my-thread2,has am.s2");
			try {
				Thread.sleep(1_000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			System.out.println("now thread2 begin am.s1");

			synchronized (am.s1){
				System.out.println("2----> Thread id="+ Thread.currentThread().getId()
						+"s1="+am.s1+",s2="+am.s2);
			}
		}
	}
}